package com.youlv.yl.util;

/**
 * @author fenghe
 * @date 2022/1/13 16:59
 */

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Scope(scopeName = "prototype")
@ServerEndpoint("/chat/server/{nickname}")
public class CharServerUitls {
    /** 用户的昵称*/
    private String nickname;
    /** 会话对象*/
    private Session session;

    /** 记录当前的用户*/
    public static ConcurrentHashMap<String, Session> users = new ConcurrentHashMap<>();

    /** 连接-服务端*/
    @OnOpen
    public void open(@PathParam("nickname") String name, Session session) {
        if(users.containsKey(name)){
            // 昵称已被占用
            sendMsg(session, "亲，昵称已被占用！");
        } else {
            this.nickname = name;
            this.session = session;
            users.put(name, session);
            sendMoreMsg("欢迎 " + name + " 进入聊天区！");
        }
    }

    /** 监听 消息，接收消息*/
    @OnMessage
    public void message(String msg, Session session) {
        if(session != null) {
            System.out.println(session);
            System.err.println("服务器接收：" + msg);
            sendMsg(session, "已收到，时间：" + DateUtils.CurrentTime());
            sendMoreMsg(nickname + "：" + msg);
        }
        sendMsg(session, "消息拒绝发送");
    }

    /** 异常监听，只要出错误*/
    @OnError
    public void error(Throwable throwable) {
        System.err.println("出错了");
    }

    /** 监听关闭*/
    @OnClose
    public void close(@PathParam("nickname") String name) {
        if (name != null) {
            users.remove(name);
            sendMoreMsg("让我们掌声欢送 " + name + " 的离开！");
        }
    }

    /** 发送单条消息*/
    private void sendMsg(Session session, String msg) {
        try {
            session.getBasicRemote().sendText(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /** 群发消息*/
    private static void sendMoreMsg(String msg) {
        // 发送消息
        for(String s : users.keySet()) {
            try {
                users.get(s).getBasicRemote().sendText(msg);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /** 推送消息*/
    public static boolean pushMsg(String msg) {
        sendMoreMsg(msg);
        return true;
    }
}
